package com.ysc.task.task;

import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;

/**
 * Version: 1.0
 * Class Name: DynamicTaskManager
 * Description: 定时任务
 * Author: ysc
 * Date: 2024/3/31 11:00
 */

@Component
public class DynamicTaskManager implements SchedulingConfigurer{

    private final Map<String, ScheduledFuture<?>> scheduledTasks = new ConcurrentHashMap<>();
    private ScheduledTaskRegistrar taskRegistrar;

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        this.taskRegistrar = taskRegistrar;
    }

    public void addTask(String taskId, Runnable task, String cronExpression) {
        ScheduledFuture<?> scheduledTask = taskRegistrar.getScheduler().schedule(task, new CronTrigger(cronExpression));
        scheduledTasks.put(taskId, scheduledTask);
    }

    public void removeTask(String taskId) {
        ScheduledFuture<?> scheduledTask = scheduledTasks.get(taskId);
        if (scheduledTask != null) {
            scheduledTask.cancel(true);
            scheduledTasks.remove(taskId);
        }
    }
}
